"""
态势对象关系 Pydantic Schema 定义
"""
from typing import Optional, Dict, Any, List
from uuid import UUID
from datetime import datetime
from pydantic import BaseModel, Field, field_validator


class RelationshipProperties(BaseModel):
    """关系属性"""
    weight: Optional[float] = Field(None, description="关系权重")
    confidence: Optional[float] = Field(None, ge=0, le=1, description="置信度")
    extra: Optional[Dict[str, Any]] = Field(default_factory=dict, description="其他属性")


class RelationshipCreate(BaseModel):
    """创建关系请求"""
    source_object_id: UUID = Field(..., description="源对象ID")
    target_object_id: UUID = Field(..., description="目标对象ID")
    relationship_type: str = Field(..., min_length=1, max_length=100, description="关系类型")
    properties: Optional[Dict[str, Any]] = Field(default_factory=dict, description="关系属性")
    description: Optional[str] = Field(None, max_length=500, description="关系描述")

    @field_validator("source_object_id", "target_object_id")
    @classmethod
    def validate_not_same(cls, v, info):
        """验证源对象和目标对象不能相同"""
        if info.field_name == "target_object_id":
            source = info.data.get("source_object_id")
            if source and v == source:
                raise ValueError("源对象和目标对象不能相同")
        return v


class RelationshipUpdate(BaseModel):
    """更新关系请求"""
    relationship_type: Optional[str] = Field(None, min_length=1, max_length=100, description="关系类型")
    properties: Optional[Dict[str, Any]] = Field(None, description="关系属性")
    description: Optional[str] = Field(None, max_length=500, description="关系描述")


class RelationshipResponse(BaseModel):
    """关系响应"""
    id: UUID
    source_object_id: UUID
    target_object_id: UUID
    relationship_type: str
    relationship_level: int
    properties: Dict[str, Any] = Field(default_factory=dict)
    description: Optional[str] = None

    # 关联对象信息
    source_object_name: Optional[str] = None
    source_object_code: Optional[str] = None
    target_object_name: Optional[str] = None
    target_object_code: Optional[str] = None

    # 审计字段
    created_at: datetime
    updated_at: datetime
    created_by: Optional[str] = None
    updated_by: Optional[str] = None

    model_config = {"from_attributes": True}


class RelationshipListResponse(BaseModel):
    """关系列表响应"""
    total: int = Field(..., description="总数")
    items: List[RelationshipResponse] = Field(..., description="关系列表")
    page: int = Field(..., description="当前页码")
    page_size: int = Field(..., description="每页数量")


class RelationshipFilter(BaseModel):
    """关系筛选条件"""
    source_object_id: Optional[UUID] = None
    target_object_id: Optional[UUID] = None
    relationship_type: Optional[str] = None
    relationship_level: Optional[int] = Field(None, ge=1, le=5)


class RelationshipTreeNode(BaseModel):
    """关系树节点"""
    object_id: UUID
    object_name: str
    object_code: Optional[str] = None
    object_type: str
    relationship_type: Optional[str] = None
    relationship_id: Optional[UUID] = None
    level: int = Field(..., ge=1, le=5)
    children: List["RelationshipTreeNode"] = Field(default_factory=list)

    model_config = {
        "json_schema_extra": {
            "example": {
                "object_id": "123e4567-e89b-12d3-a456-426614174000",
                "object_name": "示例对象",
                "object_code": "OBJ-001",
                "object_type": "weapon",
                "relationship_type": "隶属于",
                "relationship_id": "123e4567-e89b-12d3-a456-426614174001",
                "level": 1,
                "children": []
            }
        }
    }


# 解决前向引用问题
RelationshipTreeNode.model_rebuild()


class CycleCheckRequest(BaseModel):
    """循环依赖检测请求"""
    source_object_id: UUID = Field(..., description="源对象ID")
    target_object_id: UUID = Field(..., description="目标对象ID")
    relationship_type: str = Field(..., description="关系类型")


class CycleCheckResponse(BaseModel):
    """循环依赖检测响应"""
    has_cycle: bool = Field(..., description="是否存在循环")
    cycle_path: Optional[List[UUID]] = Field(None, description="循环路径")
    message: str = Field(..., description="检测结果消息")


class GraphExportRequest(BaseModel):
    """知识图谱导出请求"""
    object_ids: Optional[List[UUID]] = Field(None, description="要导出的对象ID列表,为空则导出全部")
    include_relationships: bool = Field(default=True, description="是否包含关系")
    clear_existing: bool = Field(default=False, description="是否清除已存在的数据")


class GraphExportResponse(BaseModel):
    """知识图谱导出响应"""
    success: bool = Field(..., description="是否成功")
    objects_exported: int = Field(..., description="导出的对象数量")
    relationships_exported: int = Field(..., description="导出的关系数量")
    errors: List[str] = Field(default_factory=list, description="错误信息")
    message: str = Field(..., description="结果消息")


class RelationshipTypeItem(BaseModel):
    """关系类型项"""
    value: str = Field(..., description="关系类型值")
    label: str = Field(..., description="关系类型中文标签")
    category: str = Field(..., description="关系类型分类")


class RelationshipTypeResponse(BaseModel):
    """关系类型响应"""
    categories: List[RelationshipTypeItem] = Field(..., description="关系类型列表")


def get_relationship_types():
    """获取所有关系类型及其中文标签"""
    relationship_mapping = {
        # 指挥隶属关系
        "subordinate_to": ("隶属于", "指挥隶属"),
        "command": ("指挥", "指挥隶属"),
        "jurisdiction": ("管辖", "指挥隶属"),

        # 部署与位置关系
        "deployed_at": ("部署在", "部署位置"),
        "stationed_at": ("驻扎", "部署位置"),
        "patrols": ("巡逻", "部署位置"),
        "docked_at": ("停靠", "部署位置"),

        # 支援与协同关系
        "supports": ("支援", "支援协同"),
        "coordinates_with": ("协同", "支援协同"),
        "attached_to": ("配属", "支援协同"),
        "cooperates_with": ("配合", "支援协同"),

        # 保障与补给关系
        "supplies": ("补给", "保障补给"),
        "maintains": ("维修", "保障补给"),
        "transports": ("运输", "保障补给"),
        "provides_logistics": ("后勤保障", "保障补给"),

        # 观测与侦察关系
        "monitors": ("监视", "观测侦察"),
        "reconnaissance": ("侦察", "观测侦察"),
        "tracks": ("跟踪", "观测侦察"),
        "observes": ("观察", "观测侦察"),

        # 目标与观测能力关系（新增）
        "detects": ("探测到", "目标观测"),
        "tracks_target": ("跟踪目标", "目标观测"),
        "identifies": ("识别", "目标观测"),
        "covers": ("覆盖", "目标观测"),

        # 防御与防护关系
        "protects": ("保护", "防御防护"),
        "guards": ("警戒", "防御防护"),
        "intercepts": ("拦截", "防御防护"),
        "provides_cover": ("掩护", "防御防护"),

        # 通信与数据关系
        "communicates_with": ("通信", "通信数据"),
        "data_link": ("数据链", "通信数据"),
        "command_chain": ("指挥链", "通信数据"),
        "intelligence_share": ("情报共享", "通信数据"),

        # 威胁与对抗关系
        "threatens": ("威胁", "威胁对抗"),
        "opposes": ("对抗", "威胁对抗"),
        "jams": ("干扰", "威胁对抗"),
        "suppresses": ("压制", "威胁对抗"),

        # 特定装备关系
        "carries": ("搭载", "装备特定"),
        "formation": ("编队", "装备特定"),
        "escorts": ("护航", "装备特定"),
        "guides": ("引导", "装备特定"),

        # 地理与基础设施关系
        "connects": ("连接", "地理设施"),
        "depends_on": ("依赖", "地理设施"),
        "controls": ("控制", "地理设施"),
        "influences": ("影响", "地理设施"),
    }

    categories = []
    for value, (label, category) in relationship_mapping.items():
        categories.append(RelationshipTypeItem(
            value=value,
            label=label,
            category=category
        ))

    return RelationshipTypeResponse(categories=categories)
